package thread;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * \* User: Administrator
 * <p>
 * \* Date: 2020/11/17
 * <p>
 * \* Time: 14:43
 * <p>
 * \* Description:
 *  读写锁 可以在业务中针对查询 做读锁   针对写入做写锁
 *  读锁不阻塞  写锁阻塞
 *  在读锁持有期间 不能再获取写锁  写锁的获取必须在读锁释放之后
 * \
 */
public class ReadWriteLockDemo {
    private final static ReadWriteLock rwLock = new ReentrantReadWriteLock();
    private static final Lock rLock = rwLock.readLock();
    private static final Lock wLock = rwLock.writeLock();

    public static void read() throws InterruptedException {
        rLock.lock();
        System.out.println(Thread.currentThread().getName() + ":  执行读取");
        Thread.sleep(3000);
        rLock.unlock();
        write();
    }

    public static void write() throws InterruptedException {
        wLock.lock();
        System.out.println(Thread.currentThread().getName() + ": 执行写入");
        Thread.sleep(3000);
        wLock.unlock();
    }

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                try {
                    read();
//                    write();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }).start();
        }
    }
}
